<?php

namespace Goods\Controller;

use Common\Controller\AdminbaseController;

class AdminGoodsController extends AdminbaseController {
	
	protected $goods_model;
		
	function _initialize() {
		parent::_initialize();
		$this->goods_model = D("Goods/Goods");
		$this->category_model = D("Goods/GoodsCategory");
		
	}
	
	// 后台商品分类列表
    public function index(){
		
		$this->_getTree();
		
		$this->display();
	}
	
	// 后台商品分类列表
	public function ajaxgoodslist(){
		$where['is_delete'] = array('neq',3);
		
		$keyword=trim(I('keyword'));
        if($keyword)
        {
			 $where['goods_name']=array('like',"%$keyword%");			 	 
        }
		$cat_id = I('cat_id');
		if($cat_id)
		{
			$where['cat_id']=$cat_id;
		}
		$is_on_sale = I('is_on_sale');
		if($is_on_sale !== ''){
			$where['is_on_sale']=$is_on_sale;
		}
		$intro = I('intro');
		if($intro !== ''){
			$where[$intro] = 1;
		}
		
		$count=$this->goods_model->where($where)->count();		
		$page = $this->ajaxpage($count,10);								
		$order_str = "a.{$_POST['orderby1']} {$_POST['orderby2']},a.last_update DESC";
		$this->goods_model->field('a.*,b.name');
		$this->goods_model
		->alias('a')
		->join('__GOODS_CATEGORY__ b ON a.cat_id = b.id')
		->where($where)
		->limit($page->firstRow , $page->listRows)			
		->order($order_str);		
		
		$goodslist = $this->goods_model->select();
		
		//print_r($goodslist);die;
		$this->assign('goodslist',$goodslist);
		$this->assign('page',$page->show('Admin'));
		$this->display();
	}
	
	public function _getTree(){
		$tree = new \Tree();
	 	$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
	 	$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	 	$category = $this->category_model->order(array("parent_id_path"=>"asc"))->select();
	 	
	 	$new_category=array();
	 	foreach ($category as $r) {
	 		$r['id']=$r['id'];
	 		$r['parentid']=$r['parent_id'];
	 		$r['selected']= (!empty($parentid) && $r['id']==$parentid)? "selected":"";
	 		$new_category[] = $r;
	 	}
	 	$tree->init($new_category);
	 	$tree_tpl="<option value='\$id' \$selected>\$spacer\$name</option>";
	 	$tree=$tree->get_tree(0,$tree_tpl);
	 	
	 	$this->assign("category_tree",$tree);
	}
	
	public function add(){
		//商品分类
		$tree = new \Tree();
	 	$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
	 	$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	 	$category = $this->category_model->order(array("parent_id_path"=>"asc"))->select();
	 	
	 	$new_category=array();
	 	foreach ($category as $r) {
	 		$r['id']=$r['id'];
	 		$r['parentid']=$r['parent_id'];
	 		$r['selected']= (!empty($parentid) && $r['id']==$parentid)? "selected":"";
	 		$new_category[] = $r;
	 	}
	 	$tree->init($new_category);
	 	$tree_tpl="<option value='\$id' \$selected>\$spacer\$name</option>";
	 	$tree=$tree->get_tree(0,$tree_tpl);
		
		//商品类型
		$goods_type = M('GoodsType')->select();
	 	
	 	$this->assign("category_tree",$tree);
		$this->assign("goods_type",$goods_type);
		$this->display();
	}
	
	//ajax获取规格
	public function ajaxGetSpec(){
		$id = I("get.type_id",0,'intval');
		$goods_id = I("get.id",0,'intval');
		$spec = M('Spec')->where(array("type_id"=>$id))->order(array("order"=>"asc"))->select();
		
		foreach($spec as $key=>$v){
			$spec[$key]['items'] = M('SpecItem')->where(array("spec_id"=>$v['id']))->getField('id,item');
		}
		
		//获取规格id		
		$items_id = M('GoodsSku')->where(array("goods_id"=>$goods_id))->getField("GROUP_CONCAT(`item_path` SEPARATOR '-') AS items_id");		
        $items_ids = explode('-', $items_id); 		
		
		$this->assign('spec',$spec);
		$this->assign('items_ids',$items_ids);
		$this->assign("goods_id",$goods_id);
		$this->display("ajaxspec");
	}
	
	/**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */    
    public function ajaxGetSpecInput(){     
         $GoodsLogic = new \Goods\Logic\GoodsLogic();
		
         $goods_id = I("goods_id",0,'intval');
         $str = $GoodsLogic->getSpecInput($goods_id ,$_POST['spec_arr']);
         exit($str);   
    }
	
	public function add_post(){
		if(IS_POST){
													
				if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
				foreach ($_POST['photos_url'] as $key=>$url){
					$photourl=sp_asset_relative_url($url);
					$img['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
					}
				}
								
				$data = I("post.post");
				if($data['goods_name'] == ''){
					$this->error("商品名称不能为空！");
				}
				if($data['cat_id'] == '' || $data['cat_id'] == 0){
					$this->error("请选择分类！");
				}
				$data['photo'] = json_encode($img['photo']);
				$data['goods_content'] = htmlspecialchars_decode($data['goods_content']);
				$data['last_update'] = time();
				$data['on_time'] = $data['is_on_sale'] == 1 ? time() : '';
				$result=$this->goods_model->add($data);
								
				$this->goods_model->addGoodsSku($result);//添加规格
				$this->goods_model->addSpecImg($result);//添加规格图片
								
				if ($result) {
					$this->success("添加成功！");
				} else {
					$this->error("添加失败！");
				}			
		}
	}
	
	public function edit(){
		
		$id = I("get.id",0,'intval');
		$data=$this->goods_model->where(array("goods_id" => $id))->find();
		
		$tree = new \Tree();
	 	$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
	 	$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	 	$category = $this->category_model->order(array("parent_id_path"=>"asc"))->select();
	 	$cat_id = $data['cat_id'];
	 	$new_category=array();
	 	foreach ($category as $r) {
	 		$r['id']=$r['id'];	 		
	 		$r['selected']= (!empty($cat_id) && $r['id']==$cat_id)? "selected":"";
	 		$new_category[] = $r;
	 	}
	 	$tree->init($new_category);
	 	$tree_tpl="<option value='\$id' \$selected>\$spacer\$name</option>";
	 	$tree=$tree->get_tree(0,$tree_tpl);
		
		//商品类型
		$goods_type = M('GoodsType')->select();
	 		 					
		$this->assign("category_tree",$tree);
		$this->assign("data",$data);
		$this->assign("photo",json_decode($data['photo'],true));
		$this->assign("goods_type",$goods_type);		
		$this->display();
	}
	
	public function edit_post(){
		if(IS_POST){
			//$id = intval($_POST['post']['goods_id']);
			if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
				foreach ($_POST['photos_url'] as $key=>$url){
					$photourl=sp_asset_relative_url($url);
					$img['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
					}
				}
								
				$data = I("post.post");
				if($data['goods_name'] == ''){
					$this->error("商品名称不能为空！");
				}
				if($data['cat_id'] == '' || $data['cat_id'] == 0){
					$this->error("请选择分类！");
				}
				$data['photo'] = json_encode($img['photo']);
				$data['goods_content'] = htmlspecialchars_decode($data['goods_content']);
				$data['last_update'] = time();
				$data['on_time'] = $data['is_on_sale'] == 1 ? time() : '';
				$result=$this->goods_model->save($data);
				$this->goods_model->addGoodsSku($_POST['post']['goods_id']);//添加规格
				$this->goods_model->addSpecImg($_POST['post']['goods_id']);//添加规格图片
				delDir('./data/upload/goods/thumb/'.$data['goods_id']);
				if ($result) {
					$this->success("保存成功！");
				} else {
					$this->error("保存失败！");
				}
		}
	}
	
	//放入回收站
	public function delete(){
		$id = $_GET['id'];
		$result = $this->goods_model->where("goods_id = $id")->save(array('is_delete'=>3));
		if($result){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
	
	public function delete_all(){
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			
			if ($this->goods_model->where(array('goods_id'=>array('in',$ids)))->save(array('is_delete'=>3))!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}
	
	//回收站列表
	public function recyle(){
		
		$this->display();
	}
	
	public function ajaxrecyle(){
		$where['is_delete'] = '3';
		$keyword=trim(I('keyword'));
        if($keyword)
        {
			 $where['goods_name']=array('like',"%$keyword%");			 	 
        }
		$count=$this->goods_model->where($where)->count();		
		$page = $this->ajaxpage($count,10);
		$this->goods_model
		->where($where)
		->limit($page->firstRow , $page->listRows)
		->order("goods_id DESC");		
		
		$goodslist = $this->goods_model->select();
		
		$this->assign('goodslist',$goodslist);
		$this->assign('page',$page->show('Admin'));
		
		$this->display();
	}
	
	//还原
	public function restore(){
		$id = $_GET['id'];
		$result = $this->goods_model->where("goods_id = $id")->save(array('is_delete'=>0));
		if($result){
			$this->success('还原成功');
		}else{
			$this->error('还原失败');
		}
	}
	
	//删除
	public function clean(){
		$id = $_GET['id'];
		$result = $this->goods_model->where(array("goods_id" => $id,"is_delete"=>3))->delete();
		M('GoodsSku')->where(array("goods_id" => $id))->delete();//删除产品sku
		M('SpecImg')->where(array("goods_id" => $id))->delete();//删除规格图片
		if($result){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
	
	public function clean_all(){
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			M('GoodsSku')->where(array('goods_id'=>array('in',$ids)))->delete();//删除产品sku
			M('SpecImg')->where(array('goods_id'=>array('in',$ids)))->delete();//删除规格图片
			if ($this->goods_model->where(array('goods_id'=>array('in',$ids),"is_delete"=>3))->delete()!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}
	
	/**
     * ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
     * table,id_name,id_value,field,value
     */
    public function changeTableVal(){  	
            $table = I('table'); // 表名
            $id_name = I('id_name'); // 表主键id名
            $id_value = I('id_value'); // 表主键id值
            $field  = I('field'); // 修改哪个字段
            $value  = I('value'); // 修改字段值                        
            M($table)->where("$id_name = $id_value")->save(array($field=>$value)); // 根据条件保存修改的数据
    }
	
}